using Microsoft.AspNetCore.Http;
using System.Text.RegularExpressions;

namespace Terra.Core.Common.Utils;

/// <summary>
/// HTTP上下文工具类
/// </summary>
public static class HttpContextUtils
{
    /// <summary>
    /// 获取客户端IP地址
    /// </summary>
    /// <param name="context">HTTP上下文</param>
    /// <returns>IP地址</returns>
    public static string GetClientIpAddress(HttpContext context)
    {
        if (context == null) return string.Empty;

        string ip = context.Request.Headers["X-Forwarded-For"].ToString();
        if (string.IsNullOrEmpty(ip))
        {
            ip = context.Request.Headers["X-Real-IP"].ToString();
        }
        if (string.IsNullOrEmpty(ip))
        {
            ip = context.Connection.RemoteIpAddress?.ToString();
        }

        if (string.IsNullOrEmpty(ip))
        {
            return "未知IP";
        }

        // 如果是多个IP，取第一个
        return ip.Contains(",") ? ip.Split(',')[0].Trim() : ip.Trim();
    }

    /// <summary>
    /// 获取客户端浏览器信息
    /// </summary>
    /// <param name="context">HTTP上下文</param>
    /// <returns>浏览器信息</returns>
    public static (string browser, string os) GetClientInfo(HttpContext context)
    {
        if (context == null) return ("未知浏览器", "未知系统");

        var userAgent = context.Request.Headers["User-Agent"].ToString();
        if (string.IsNullOrEmpty(userAgent))
        {
            return ("未知浏览器", "未知系统");
        }

        // 解析操作系统
        string os = "未知系统";
        if (userAgent.Contains("Windows"))
        {
            os = Regex.Match(userAgent, @"Windows NT [0-9\.]+").Value;
        }
        else if (userAgent.Contains("Mac"))
        {
            os = Regex.Match(userAgent, @"Mac OS X [0-9_\.]+").Value;
        }
        else if (userAgent.Contains("Linux"))
        {
            os = "Linux";
        }
        else if (userAgent.Contains("Android"))
        {
            os = Regex.Match(userAgent, @"Android [0-9\.]+").Value;
        }
        else if (userAgent.Contains("iOS"))
        {
            os = Regex.Match(userAgent, @"iOS [0-9\.]+").Value;
        }

        // 解析浏览器
        string browser = "未知浏览器";
        if (userAgent.Contains("Edge"))
        {
            browser = "Microsoft Edge";
        }
        else if (userAgent.Contains("Chrome"))
        {
            browser = "Chrome";
        }
        else if (userAgent.Contains("Firefox"))
        {
            browser = "Firefox";
        }
        else if (userAgent.Contains("Safari"))
        {
            browser = "Safari";
        }
        else if (userAgent.Contains("Opera"))
        {
            browser = "Opera";
        }
        else if (userAgent.Contains("MSIE") || userAgent.Contains("Trident"))
        {
            browser = "Internet Explorer";
        }

        return (browser, os);
    }
}